<!-- src/views/common/OrderDetail.vue -->
<template>
  <StoreHeader></StoreHeader>
  
  <div class="order-detail-container">
    <el-card class="order-card">
      <template #header>
        <div class="order-header">
          <span class="order-title">订单详情</span>
          <el-tag :type="getOrderStatusType(orderInfo.orderStatus)" size="large">
            {{ getOrderStatusText(orderInfo.orderStatus) }}
          </el-tag>
        </div>
      </template>
      
      <el-row :gutter="20">
        <!-- 订单信息 -->
        <el-col :span="24">
          <el-descriptions title="订单信息" :column="2" border>
            <el-descriptions-item label="订单编号">{{ orderInfo.orderNum }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ orderInfo.createTime }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getOrderStatusType(orderInfo.orderStatus)">
                {{ getOrderStatusText(orderInfo.orderStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="支付时间">{{ orderInfo.payTime || '未支付' }}</el-descriptions-item>
          </el-descriptions>
          
          <el-descriptions title="商品信息" :column="2" border class="mt-20">
            <el-descriptions-item label="商品名称">{{ orderInfo.productName }}</el-descriptions-item>
            <el-descriptions-item label="单价">
              <span class="amount">¥{{orderInfo.productPrice}}</span>
            </el-descriptions-item>
            <!-- <el-descriptions-item label="商品描述">{{ orderInfo.productNum }}</el-descriptions-item> -->
            <el-descriptions-item label="商品描述">{{ orderInfo.productDesc }}</el-descriptions-item>
          </el-descriptions>
          
          <el-descriptions title="收货信息" :column="2" border class="mt-20">
            <el-descriptions-item label="收货人">{{ orderInfo.customerName }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ orderInfo.customerPhone }}</el-descriptions-item>
            <el-descriptions-item label="收货地址" :span="2">{{ orderInfo.customerLocation }}</el-descriptions-item>
          </el-descriptions>
          
          <!-- 操作按钮模块 -->
          <div class="action-buttons">
            <template v-if="orderInfo.orderStatus === '0'">
              <el-button 
                type="primary" 
                size="large" 
                @click="paymentConfirm"
                class="pay-button"
              >
                立即支付 ¥{{ orderInfo.productPrice }}
              </el-button>
              <el-button @click="cancelOrder">取消订单</el-button>
            </template>

            <template v-else-if="orderInfo.orderStatus === '1'">
              <el-button 
                type="success" 
                size="large" 
                @click="confirmReceipt"
                class="pay-button"
              >
                确认收货
              </el-button>
              <el-button @click="showComplaintDialog = true">投诉订单</el-button>
            </template>

            <template v-else-if="orderInfo.orderStatus === '2'">
              <el-button 
                v-if="orderInfo.evaluationed === 1"
                type="primary" 
                size="large" 
                @click="openModifyEvaluationDialog"
                class="pay-button"
              >
                修改评价
              </el-button>
              <el-button 
                v-else
                type="success" 
                size="large" 
                @click="showEvaluationDialog = true"
                class="pay-button"
              >
                评价商品
              </el-button>
              <el-button @click="showComplaintDialog = true">投诉订单</el-button>
            </template>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
  
  <!-- 评价商品对话框 -->
  <el-dialog
    v-model="showEvaluationDialog"
    title="评价商品"
    width="500px"
    :before-close="handleEvaluationCancel"
  >
    <el-form
      ref="evaluationFormRef"
      :model="evaluationForm"
      :rules="evaluationRules"
      label-width="80px"
    >
      <el-form-item label="评分" prop="evaluationLevel">
        <el-rate
          v-model="evaluationForm.evaluationLevel"
          :max="5"
          :allow-half="false"
          :show-text="true"
          :texts="['很差', '较差', '一般', '推荐', '力荐']"
        />
      </el-form-item>
      
      <el-form-item label="评价内容" prop="evaluationContent">
        <el-input
          v-model="evaluationForm.evaluationContent"
          type="textarea"
          :rows="4"
          placeholder="请输入您的评价内容..."
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleEvaluationCancel">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitEvaluation"
          :loading="evaluationLoading"
        >
          提交评价
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 投诉订单对话框 -->
  <el-dialog
    v-model="showComplaintDialog"
    title="投诉订单"
    width="500px"
    :before-close="handleComplaintCancel"
  >
    <el-form
      ref="complaintFormRef"
      :model="complaintForm"
      :rules="complaintRules"
      label-width="80px"
    >
      <el-form-item label="投诉类型" prop="type">
        <el-select
          v-model="complaintForm.type"
          placeholder="请选择投诉类型"
          style="width: 100%;"
        >
          <el-option label="商品质量问题" value="quality"></el-option>
          <el-option label="物流问题" value="logistics"></el-option>
          <el-option label="服务态度问题" value="service"></el-option>
          <el-option label="其他问题" value="other"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="投诉描述" prop="description">
        <el-input
          v-model="complaintForm.description"
          type="textarea"
          :rows="4"
          placeholder="请详细描述您的投诉内容..."
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="上传证据">
        <el-upload
          action="#"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :auto-upload="false"
          multiple
          :limit="3"
          accept=".jpg,.jpeg,.png"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        
        <el-dialog v-model="dialogVisible" append-to-body>
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleComplaintCancel">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitComplaint"
          :loading="complaintLoading"
        >
          提交投诉
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import StoreHeader from '@/components/common/StoreHeader.vue'
import { getByPathVariable, postByData } from '@/api/common/base'
import { getOrderStatusText,getOrderStatusType } from '@/utils/DataTextMap'

const route = useRoute()

// 订单信息
const orderInfo = ref({})

// 评价对话框相关
const showEvaluationDialog = ref(false)
const evaluationFormRef = ref()
const evaluationLoading = ref(false)

const evaluationForm = reactive({
  evaluationLevel: 5,
  evaluationContent: '',
  productNum:''
})

const evaluationRules = {
  evaluationLevel: [
    { required: true, message: '请选择评分', trigger: 'change' }
  ],
  evaluationContent: [
    { required: true, message: '请输入评价内容', trigger: 'blur' },
    { min: 5, max: 200, message: '评价内容长度应在5到200个字符之间', trigger: 'blur' }
  ]
}

const requestSubmit = async (status) => {
  try {
    const res = await postByData('/business/submit/order', {
      orderNum: orderInfo.value.orderNum,
      dataVersion: orderInfo.value.dataVersion,
      submitType: status
    })
    
    if(res.code == 200) { 
      setTimeout(() => {
        window.location.reload()
      }, 1000)
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 处理支付确认
const paymentConfirm = () => {
  ElMessageBox.confirm(
    '确认支付 ¥'+orderInfo.value.productPrice+' 购买 '+orderInfo.value.productName+' 吗？',
    '确认支付',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    requestSubmit(1)
  }).catch(() => {
    // 用户取消操作
  })
}

// 取消订单
const cancelOrder = () => {
  ElMessageBox.confirm('确定要取消该订单吗？', '确认取消', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    try {
    const res = await postByData('/business/cancel/order', {
      orderNum: orderInfo.value.orderNum,
      dataVersion: orderInfo.value.dataVersion,
      submitType: 2
    })
    
    if(res.code == 200) { 
      setTimeout(() => {
        window.location.reload()
      }, 1000)
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
  }).catch(() => {
    // 用户取消操作
  })
}

// 确认收货
const confirmReceipt = () => {
  ElMessageBox.confirm('确认收到商品了吗？', '确认收货', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    requestSubmit(3)
  }).catch(() => {
    // 用户取消操作
  })
}

// 投诉对话框相关
const showComplaintDialog = ref(false)
const complaintFormRef = ref()
const complaintLoading = ref(false)
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const complaintForm = reactive({
  type: '',
  description: ''
})

const complaintRules = {
  type: [
    { required: true, message: '请选择投诉类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入投诉描述', trigger: 'blur' },
    { min: 10, max: 500, message: '投诉描述长度应在10到500个字符之间', trigger: 'blur' }
  ]
}

// 处理投诉取消
const handleComplaintCancel = () => {
  ElMessageBox.confirm('确定要取消投诉吗？', '确认取消', {
    confirmButtonText: '确定',
    cancelButtonText: '继续投诉',
    type: 'warning'
  }).then(() => {
    showComplaintDialog.value = false
    // 重置表单
    complaintForm.type = ''
    complaintForm.description = ''
  }).catch(() => {
    // 继续投诉
  })
}

// 提交投诉
const submitComplaint = async () => {
  if (!complaintFormRef.value) return
  
  await complaintFormRef.value.validate(async (valid) => {
    if (valid) {
      complaintLoading.value = true
      try {
        // 这里应该调用提交投诉的API
        // 示例: await postByData('/business/complaint/submit', { ...complaintForm })
        
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        ElMessage.success('投诉提交成功')
        showComplaintDialog.value = false
        
        // 重置表单
        complaintForm.type = ''
        complaintForm.description = ''
      } catch (error) {
        ElMessage.error('投诉提交失败')
      } finally {
        complaintLoading.value = false
      }
    }
  })
}

// 图片预览处理
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleRemove = (file) => {
  console.log(file)
}

// 显示评价对话框
const handleEvaluationCancel = () => {
  ElMessageBox.confirm('确定要取消评价吗？', '确认取消', {
    confirmButtonText: '确定',
    cancelButtonText: '继续评价',
    type: 'warning'
  }).then(async() => {
    showEvaluationDialog.value = false
    // 重置表单
    evaluationForm.evaluationLevel = 5
    evaluationForm.productNum = ''
    evaluationForm.evaluationContent = ''
  }).catch(() => {
    // console.log(orderInfo.value.productNum);
    
    // 继续评价
  })
}

// 打开修改评价对话框
const openModifyEvaluationDialog = async () => {
  try {
    // 这里可以根据实际情况获取用户的历史评价信息
    // 例如：const res = await getByPathVariable('/business/evaluation/info', orderInfo.value.orderNum)
    
    // 模拟获取历史评价数据
    // 实际项目中应该从API获取用户的历史评价
    evaluationForm.evaluationLevel = 5 // 假设历史评价是5星
    evaluationForm.evaluationContent = '' // 假设历史评价内容
    
    showEvaluationDialog.value = true
  } catch (error) {
    ElMessage.error('获取历史评价失败')
  }
}

// 提交评价
const submitEvaluation = async () => {
  if (!evaluationFormRef.value) return
  
  await evaluationFormRef.value.validate(async (valid) => {
    if (valid) {
      evaluationLoading.value = true
      try {
        evaluationForm.productNum=orderInfo.value.productNum
        
        // 判断是新增评价还是修改评价
        const isModify = orderInfo.value.evaluationed === 1
        
        // 如果是修改评价，可以传递额外的标识或调用不同的API
        const apiUrl = isModify ? '/business/comment/update' : '/business/comment/product'
        
        await postByData(apiUrl, {
          ...evaluationForm,
          orderNum: orderInfo.value.orderNum,
          isModify: isModify
        })
        
        showEvaluationDialog.value = false
        
        // 重置表单
        evaluationForm.evaluationLevel = 5
        evaluationForm.evaluationContent = ''
        
        // 显示成功消息
        ElMessage.success(isModify ? '评价修改成功' : '评价提交成功')
        
        // 重新加载订单详情，更新状态
        setTimeout(() => {
          fetchOrderDetail(orderInfo.value.orderNum)
        }, 500)
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        evaluationLoading.value = false
      }
    }
  })
}

// 获取订单详情
const fetchOrderDetail = async (orderId) => {
  try {
    const res = await getByPathVariable('/business/order/info', orderId)
    if(!res.data) window.history.back()
    orderInfo.value = res.data
  } catch (error) {
    ElMessage.error('订单详情获取失败')
  }
}

// 页面加载时获取订单详情
onMounted(() => {
  const orderId = route.params.orderNum
  if (orderId) {
    fetchOrderDetail(orderId)
  }
})
</script>

<style scoped>
.order-detail-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.order-header {
  display: flex;
  /*justify-evaluationContent: flex-end;*/
  align-items: center;
  /* width: 100%; */
}

.order-title {
  font-size: 18px;
  font-weight: bold;
}

.mt-20 {
  margin-top: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  /*justify-evaluationContent: flex-end;*/
  margin-top: 50px;
}

.pay-button {
  width: 200px;
}

.amount {
  font-weight: bold;
}

:deep(.el-descriptions__label) {
  width: 120px;
}

.dialog-footer {
  display: flex;
  /*justify-evaluationContent: flex-end;*/
  gap: 10px;
}
</style>